<template>
	<div class="page-container">
		<!-- 表单内容区 -->
		<scroll-view class="form-scroll" scroll-y>
			<view class="form-wrapper">
				
				<!-- 头像上传区域 -->
				<view class="avatar-section">
					<view class="avatar-upload-container">
						<van-uploader 
							:file-list="fileList" 
							max-count="1" 
							@delete="deleteImages" 
							@after-read="afterRead"
							class="avatar-uploader"
						>
							<view v-if="fileList.length === 0" class="avatar-placeholder">
								<van-icon name="camera" size="32" color="#666" />
								<text class="upload-text">点击上传头像</text>
							</view>
						</van-uploader>
					</view>
				</view>
				
				<!-- 表单字段区域 -->
				<van-cell-group class="form-fields">
					<!-- 用户名 -->
					<van-field 
						:value="obj.userName" 
						placeholder="请输入用户名" 
						label="用户名"
						@change="changeInput($event, 'userName')" 
						class="form-field"
						border="none"
					/>

					<!-- 昵称 -->
					<van-field 
						:value="obj.nickname" 
						placeholder="请输入昵称" 
						label="昵称"
						@change="changeInput($event, 'nickname')" 
						class="form-field"
						border="none"
					/>

					<!-- 邮箱 -->
					<van-field 
						:value="obj.email" 
						placeholder="请输入邮箱" 
						label="邮箱"
						type="email"
						@change="changeInput($event, 'email')" 
						class="form-field"
						border="none"
					/>

					<!-- 留言 -->
					<van-field 
						:value="obj.ramk" 
						placeholder="请输入留言" 
						label="留言"
						@change="changeInput($event, 'ramk')" 
						class="form-field"
						border="none"
					/>

					<!-- 账号 -->
					<van-field 
						:value="obj.accountNumber" 
						placeholder="请输入账号" 
						label="账号"
						@change="changeInput($event, 'accountNumber')" 
						class="form-field"
						border="none"
					/>

					<!-- 密码 -->
					<van-field 
						:value="obj.password" 
						placeholder="请输入密码" 
						label="密码"
						type="password"
						@change="changeInput($event, 'password')" 
						class="form-field"
						border="none"
					/>

					<!-- 统一风格的角色选择字段 -->
					<van-field 
						class="form-field"
						style="width: 100vw"
						border="none"
						label="角色"
						v-if="userInfo.roleId == '68db8479c3b5c9ccb0dfdf38'"
					>
						<template #input>
							<view class="role-selector" @click="toggleRoleSelector">
								<text class="selected-role-text" :class="{ 'placeholder-text': !selectedRoleName }">
									{{ selectedRoleName || '请选择角色' }}
								</text>
								<van-icon name="arrow-down" class="dropdown-icon" :rotate="roleSelectorShow ? 180 : 0" />
							</view>
						</template>
					</van-field>
					
					<!-- 角色下拉面板 (绝对定位在表单内部) -->
					<view class="role-dropdown-panel" v-if="roleSelectorShow">
						<view class="search-container">
							<van-search 
								v-model="roleSearch" 
								placeholder="搜索角色..." 
								shape="round"
								class="role-search"
								@input="filterRoles"
							/>
						</view>
						<view class="role-list">
							<view 
								class="role-item" 
								v-for="role in filteredRoles" 
								:key="role.value"
								@click="selectRole(role)"
								:class="{ 'selected': role.value === obj.roleId }"
							>
								<van-icon :name="role.icon || 'user'" class="role-icon" />
								<text class="role-name">{{ role.text }}</text>
								<van-icon name="checked" class="check-icon" v-if="role.value === obj.roleId" />
							</view>
							<view class="role-item" @click="selectRole({value: '', text: '无角色'})" :class="{ 'selected': !obj.roleId }">
								<van-icon name="user-o" class="role-icon" />
								<text class="role-name">无角色</text>
								<van-icon name="checked" class="check-icon" v-if="!obj.roleId" />
							</view>
						</view>
					</view>
				</van-cell-group>
			</view>
		</scroll-view>

		<!-- 底部保存按钮 -->
		<view class="bottom-button-container">
			<button class="save-button" @click="save">
				<van-icon name="check" class="button-icon" />
				保存
			</button>
		</view>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				obj: {
					gender: '男',
					roleId: ''
				},
				userInfo: {},
				fileList: [],
				id: '',
				// 角色相关数据
				roles: [],
				roleOptions: [],
				selectedRoleName: '',
				// 角色选择器状态
				roleSelectorShow: false,
				roleSearch: '',
				filteredRoles: []
			};
		},

		onLoad(option) {
			this.userInfo = uni.getStorageSync("userInfo");
			if (option.id) {
				this.id = option.id;
				this.getInit();
			} else {
				// 新增用户时加载角色列表
				this.loadRoles();
			}
		},

		methods: {
			// 初始化数据
			getInit() {
				this.$axios("overallSituation", {
					state: "look",
					databaseName: "userList",
					_id: this.id,
				}).then((result) => {
					this.obj = result.data[0] || {};
					// 加载头像
					if (this.obj.headImage) {
						this.fileList = [{ url: this.obj.headImage }];
					}
					// 加载角色列表并设置当前角色
					this.loadRoles().then(() => {
						this.updateSelectedRoleName();
					});
				});
			},
			
			// 加载角色列表
			async loadRoles() {
				try {
					const result = await this.$axios('overallSituation', {
						state: "look",
						databaseName: "role"
					}, true);
					if (result.code === 200) {
						this.roles = result.data || [];
						// 转换为角色选项格式，保留图标信息
						this.roleOptions = this.roles.map(role => ({
							text: role.name,
							value: role._id,
							icon: role.icon
						}));
						this.filteredRoles = [...this.roleOptions];
						this.updateSelectedRoleName();
					}
				} catch (error) {
					this.$showToast('加载角色失败');
				}
			},
			
			// 切换角色选择器显示状态
			toggleRoleSelector() {
				this.roleSelectorShow = !this.roleSelectorShow;
				// 打开时如果还没加载角色则加载
				if (this.roleSelectorShow && this.roleOptions.length === 0) {
					this.loadRoles();
				}
			},
			
			// 过滤角色
			filterRoles() {
				if (!this.roleSearch) {
					this.filteredRoles = [...this.roleOptions];
					return;
				}
				const searchStr = this.roleSearch.toLowerCase();
				this.filteredRoles = this.roleOptions.filter(role => 
					role.text.toLowerCase().includes(searchStr)
				);
			},
			
			// 选择角色
			selectRole(role) {
				this.obj.roleId = role.value;
				this.selectedRoleName = role.text;
				this.roleSelectorShow = false;
				this.roleSearch = '';
			},
			
			// 更新选中的角色名称
			updateSelectedRoleName() {
				if (!this.obj.roleId) {
					this.selectedRoleName = "";
					return;
				}
				const role = this.roleOptions.find(r => r.value === this.obj.roleId);
				this.selectedRoleName = role ? role.text : "未知角色";
				this.filteredRoles = [...this.roleOptions];
			},

			// 保存按钮
			async save() {
				if (!this.verify()) return;
				
				// 上传用户头像
				if (this.fileList.length > 0 && !this.fileList[0].url.includes("https://")) {
					try {
						let imageRes = await uniCloud.uploadFile({
							filePath: this.fileList[0].url,
							cloudPath: `用户头像/${Date.now()}${this.$getFileExtensionName(this.fileList[0].url)}`,
							header: {
								"Content-Type": "multipart/form-data",
							},
						});
						this.obj.headImage = imageRes.fileID;
					} catch (error) {
						this.$showToast("头像上传失败");
						return;
					}
				}

				this.obj.classType = this.obj.classType || false;

				try {
					let result = await this.$axios(
						"overallSituation", {
							state: this.obj._id ? "update" : "add",
							databaseName: "userList",
							createTime:this.$getTime(),
							...this.obj,
						},
						true
					);

					if (result.code === 200) {
						if (this.id == uni.getStorageSync('userInfo')._id) {
							uni.setStorageSync("userInfo", this.obj);
						}
						this.$showToast('操作成功');
						uni.navigateBack({
							delta: 1,
						});
					} else {
						this.$showToast('操作失败');
					}
				} catch (error) {
					this.$showToast('网络错误');
				}
			},

			// 校验表单信息
			verify() {
				// 检查必填字段
				if (!this.obj.userName) {
					this.$showToast('请输入用户名');
					return false;
				}
				
				if (!this.obj.accountNumber) {
					this.$showToast('请输入账号');
					return false;
				}
				
				if (!this.obj.password) {
					this.$showToast('请输入密码');
					return false;
				}

				// 检查头像
				if (this.fileList.length === 0) {
					this.$showToast('请上传用户头像');
					return false;
				}

				// 检查角色选择
				if (!this.obj.roleId) {
					this.$showToast('请选择角色');
					return false;
				}

				return true;
			},

			// 输入框内容发生变化
			changeInput(e, str) {
				this.obj[str] = e.detail;
			},

			// 文件上传
			afterRead(e) {
				// 替换现有图片
				this.fileList = [{ url: e.detail.file.url }];
			},

			// 删除图片回调函数
			deleteImages(e) {
				this.fileList = [];
			},
		},
	};
</script>

<style scoped>
	.page-container {
		min-height: 100vh;
		background-color: #f5f7fa;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
	}
	
	/* 滚动区域 */
	.form-scroll {
		height: calc(100vh - 65px); /* 减去底部按钮高度 */
	}
	
	/* 表单容器 */
	.form-wrapper {
		padding: 20px 16px;
	}
	
	/* 头像上传区域 */
	.avatar-section {
		margin: 0 auto 24px; /* 水平居中 */
		width: fit-content; /* 根据内容调整宽度 */
	}
	
	.avatar-upload-container {
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	
	.avatar-uploader {
		width: 120px !important;
		height: 120px !important;
		margin: 0 auto !important;
	}
	
	.avatar-placeholder {
		width: 120px;
		height: 120px;
		border-radius: 50%;
		background-color: #f2f3f5;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		border: 2px dashed #ddd;
		cursor: pointer;
		transition: all 0.3s ease;
	}
	
	.avatar-placeholder:hover {
		background-color: #eef0f3;
		border-color: #bbb;
	}
	
	.upload-text {
		font-size: 14px;
		color: #666;
		margin-top: 8px;
	}
	
	/* 表单字段容器 */
	.form-fields {
		background-color: #fff;
		border-radius: 12px;
		overflow: hidden;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
		position: relative; /* 为角色下拉面板提供定位参考 */
	}
	
	/* 通用表单字段样式 */
	.form-field {
		padding: 5px 20px;
		box-sizing: border-box;
		border-bottom: 1px solid #f5f5f5;
	}
	
	.form-field:last-child {
		border-bottom: none;
	}
	
	/* 角色选择字段样式 - 与其他字段统一 */
	.role-select-field {
		/* 确保与其他输入框高度一致 */
		min-height: 50px;
	}
	
	.role-selector {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 170px;
		color: #333;
		font-size: 15px;
		padding-right: 4px; /* 与其他输入框对齐 */
	}
	
	.selected-role-text {
		text-align: left;
		flex: 1;
		color: #333;
	}
	
	/* 未选择角色时的占位符样式 - 与其他输入框一致 */
	.placeholder-text {
		color: #ccc;
	}
	
	.dropdown-icon {
		color: #999;
		font-size: 18px;
		transition: transform 0.2s ease;
	}
	
	/* 角色下拉面板 - 融入表单风格 */
	.role-dropdown-panel {
		position: absolute;
		top: 100%;
		left: 0;
		right: 0;
		background-color: #fff;
		border-radius: 0 0 12px 12px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
		z-index: 10;
		max-height: 300px;
		overflow: hidden;
	}
	
	/* 搜索容器 */
	.search-container {
		padding: 10px 16px;
		border-bottom: 1px solid #f5f5f5;
	}
	
	.role-search {
		background-color: #f5f5f5;
	}
	
	/* 角色列表 */
	.role-list {
		max-height: calc(300px - 56px);
		overflow-y: auto;
	}
	
	.role-item {
		display: flex;
		align-items: center;
		padding: 12px 16px;
		border-bottom: 1px solid #f5f5f5;
		cursor: pointer;
		transition: background-color 0.2s ease;
	}
	
	.role-item:hover {
		background-color: #f5f7fa;
	}
	
	.role-item.selected {
		background-color: #e6f7ff;
	}
	
	.role-icon {
		font-size: 18px;
		color: #666;
		margin-right: 12px;
	}
	
	.role-name {
		flex: 1;
		font-size: 15px;
		color: #333;
	}
	
	.check-icon {
		color: #1890ff;
		font-size: 18px;
	}
	
	/* 底部按钮 */
	.bottom-button-container {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 12px 4%;
		background-color: #f5f7fa;
		z-index: 10;
	}
	
	.save-button {
		width: 100%;
		height: 46px;
		background-color: #007aff;
		color: #fff;
		border: none;
		border-radius: 8px;
		font-size: 16px;
		font-weight: 500;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.button-icon {
		margin-right: 8px;
	}
	
	/* 覆盖vant样式 */
	::v-deep .van-uploader__preview {
		width: 120px !important;
		height: 120px !important;
		border-radius: 50% !important;
	}
	
	::v-deep .van-uploader__preview-image {
		width: 100% !important;
		height: 100% !important;
		object-fit: cover;
		border-radius: 50% !important;
	}
	
	::v-deep .van-uploader {
		margin: 0 !important;
	}
	
	::v-deep .van-field__label {
		width: 70px !important;
		font-weight: 500;
		color: #333;
	}
	
	::v-deep .van-field__control {
		font-size: 15px;
		color: #333;
	}
	
	::v-deep .van-field__control::placeholder {
		color: #ccc;
	}
	
	/* 搜索框样式覆盖 */
	::v-deep .van-search__field {
		background-color: #f5f5f5 !important;
	}
</style>
